package org.tom.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.tom.basic.exception.MyException;
import org.tom.basic.service.impl.BaseServiceImpl;
import org.tom.user.constant.UserConstant;
import org.tom.user.domain.Logininfo;
import org.tom.user.domain.User;
import org.tom.user.mapper.LogininfoMapper;
import org.tom.user.mapper.UserMapper;
import org.tom.user.service.IUserService;
import org.tom.user.util.SaveUserAndLogininfo;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;
    
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void phoneReg(User user) {
        // 判断是否存在手机号，验证码，密码，确认的密码
        if (StringUtils.isEmpty(user.getPhone()) || StringUtils.isEmpty(user.getCode()) || StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getPasswordRepeat())){
            // 不存在提示所有的信息都要填写
            throw new MyException("请将信息填写完整");
        }

        String phone = user.getPhone();
        User userByPhone = userMapper.findByPhone(phone);



        // 两次的密码是否一致
        if (!user.getPassword().equals(user.getPasswordRepeat())){
            // 不一致提示：两次的密码不一致
            throw new MyException("两次密码不一致");
        }

        // 判断手机号是否已经存在
        if (userByPhone != null){
            // 手机号存在就提示：手机号已经存在
            throw new MyException("手机号已经被注册过");
        }
        
        // 通过前缀标识+电话号码取验证码
        Object codeByPhone = redisTemplate.opsForValue().get(UserConstant.REGISTER_PREFIX + phone);
        if (codeByPhone == null){
            // 取不到提示：请获取验证码
            throw new MyException("请获取验证码");
        }



        // 取到的验证码与输入的验证码进行判断是否一致
        String splitCode = codeByPhone.toString().split(":")[1];  // 取到的验证码
        if (!(splitCode.toLowerCase()).equalsIgnoreCase(user.getCode().toLowerCase())){ // equalsIgnoreCase判断字符串是否一致不区分大小写
            // 不一致就提示：请输入正确的验证码
            throw new MyException("请输入正确的验证码");
        }
        System.out.println("注册成功，恭喜");
        // 存入数据库
        Logininfo logininfo = SaveUserAndLogininfo.user2Logininfo(user); // 必须先添加Logininfo表格，因为在user中有字段Logininfo_id需要Logininfo的自增主键
        logininfoMapper.add(logininfo); // 添加之后返回自增主键
        user = SaveUserAndLogininfo.Logininfo2User(logininfo);
        userMapper.add(user);
    }
}
